var bearcat = require("bearcat")
var httpConf = require("../../../../http/httpModule.js")
var entryHandler = function(app) {
  this.app = app;
  this.sessionService = this.app.get('sessionService')
};
//转接HTTPS接口
entryHandler.prototype.getHttpsData = function(msg,session,next) {
	var url = msg.url
	httpConf.getHttpsData(url,function(data) {
		next(null,data)
	})
}
//微信h5获取用户信息
entryHandler.prototype.getwxuserinfo = function(msg,session,next) {
  var url = msg.url
  httpConf.getHttpsData(url,function(data) {
    data.nickname = filtration(data.nickname)
    next(null,data)
  })
}
//转接HTTP接口
entryHandler.prototype.getHttpData = function(msg,session,next) {
	var url = msg.url
	httpConf.getHttpData(url,function(data) {
		next(null,data)
	})
}
//获取微信签名
entryHandler.prototype.getSignature = function(msg,session,next) {
  var appid = msg.appid
  var url = msg.url
  httpConf.getSignature(appid,url,function(data) {
    next(null,data)
  })
}
//获取微信ticket
entryHandler.prototype.getTicket = function(msg,session,next) {
  var appid = msg.appid || "wx9e87cb229f3e0e4d"
  httpConf.getTicket(appid,next)
}
//H5登录
entryHandler.prototype.h5Enter = function(msg,session,next) {
  if(!msg.code || typeof(msg.code) !== "string"){
    next(false)
    return
  }
  var code = msg.code
  var appid = msg.appid
  httpConf.h5Enter(code,appid,0,function(data) {
    if(data.errcode){
      next(null,{"flag" : false , data : data})
      return
    }else{
    	next(null,{"flag" : true , data : data})
    }
  })
}
//微信小游戏使用临时登录凭证code 带appid 获取 session_key 和 openid
entryHandler.prototype.miniEnter = function(msg, session, next) {
  var code = msg.code
  var appid = msg.appid
  if(!code || typeof(code) !== "string" || !appid || typeof(appid) !== "string"){
    next(null,{flag : false,code: "code error || appid error"+code+":"+appid})
    return
  }
  httpConf.miniEnter(code,appid,0,function(data) {
    next(null,{"flag" : true ,data : data})
  })
}
//微信小游戏获取unionid
entryHandler.prototype.miniLogin = function(msg,session,next) {
  var openid = msg.openid
  var session_key = msg.session_key
  var encryptedData = msg.encryptedData
  var iv = msg.iv
  var unionid = httpConf.wxLogin(openid,session_key,encryptedData,iv)
  next(null,{"flag" : true ,unionid : unionid})
}
//微信app登录使用临时登录凭证code 带appid 获取 openid
entryHandler.prototype.appEnter = function(msg, session, next) {
  var code = msg.code
  var appid = msg.appid
  if(!code || typeof(code) !== "string" || !appid || typeof(appid) !== "string"){
    next(null,{flag : false,code: "code error || appid error"+code+":"+appid})
    return
  }
  httpConf.appEnter(code,appid,0,function(data) {
    next(null,{"flag" : true ,data : data})
  })
}
//登陆账号
entryHandler.prototype.entryAccount = function(msg, session, next) {
	var unionid = msg.unionid
	var self = this
	self.accountDao.getAccountInfo(msg,function(flag,userInfo) {
		if(!flag || !userInfo){
			self.accountDao.createAccount(msg,function(flag,data) {
				if(!flag || !data){
					next(null,{flag : false,msg : data})
					return
				}
				entryHandler.entrySuccess.call(self,session,data,next)
			})
		}else{
			entryHandler.entrySuccess.call(self,session,userInfo,next)
		}
	})
}
//判断账号是否存在
entryHandler.prototype.checkAccount = function(msg, session, next) {
  var unionid = msg.unionid
  var self = this
  self.accountDao.getAccountInfo(msg,function(flag,userInfo) {
    next(null,{flag:flag,userInfo:userInfo})
  })
}
//登录成功
entryHandler.entrySuccess = function(session,userInfo,next) {
	var uid = Number(userInfo.uid)
	//检查重复登录
	if( !! this.sessionService.getByUid(uid)) {
		for(var i in this.sessionService.getByUid(uid)){
			this.sessionService.kickBySessionId(this.sessionService.getByUid(uid)[i].id)
		}
	}
	session.bind(uid)
	session.set("name",userInfo.name)
	session.push("name")
	session.set("head",userInfo.head)
	session.push("head")
  session.set("limit",userInfo.limit)
  session.push("limit")
  session.set("unionid",userInfo.unionid)
  session.push("unionid")
	session.on("closed",onUserLeave.bind(this))
  userInfo.time = Date.now()
  next(null, {flag : true,msg : userInfo});
}
var onUserLeave = function(session) {
}
var filtration = function(str) {
  var strArr = str.split("")
  var result = ""
  var totalLen = 0;
  for(var idx = 0; idx < strArr.length; idx ++) {
      // 超出长度,退出程序
      if(totalLen >= 16) break;
      var val = strArr[idx];
      // 英文,增加长度1
      if(/[a-zA-Z]/.test(val)) {
          totalLen = 1 + (+totalLen);
          result += val;
      }
      // 中文,增加长度2
      else if(/[\u4e00-\u9fa5]/.test(val)) {
          totalLen = 2 + (+totalLen);
          result += val;
      }
      // 遇到代理字符,将其转换为 "口", 不增加长度
      else if(/[\ud800-\udfff]/.test(val)) {
          // 代理对长度为2,
          if(/[\ud800-\udfff]/.test(strArr[idx + 1])) {
              // 跳过下一个
              idx ++;
          }
          // 将代理对替换为 "口"
          result += "口";
      }
  }
  if(!result)
    result = "口"
  return result
}
module.exports = function(app) {
  return bearcat.getBean({
  	id : "entryHandler",
  	func : entryHandler,
  	args : [{
  		name : "app",
  		value : app
  	}],
  	props : [{
  		name : "redisDao",
  		ref : "redisDao"
  	},{
  		name : "accountDao",
  		ref : "accountDao"
  	}]
  })
};